import { Button, message } from "antd";
import { getPost, delPost } from "@/api/flandre-ui/request";
import { BasicTable, useTable, BasicColumn, TableAction } from "@/components/Table";
import DetailDrawer_AddUpdate from "./components/DrawerAddUpdate";
import { useDrawer } from "@/components/Drawer";
import "./index.less";
import { useTranslation } from "react-i18next";
import { IconEnum } from "@/enums/appEnum";

export default function PostManagement() {
	const { t } = useTranslation();
	const en_vi = "HRMS.postManagement";
	const [drawer_add_update, { openDrawer: openDrawerAddUpdate }] = useDrawer();

	// Table columns definition
	const columns: BasicColumn[] = [
		{
			title: t(`${en_vi}.jobPositionType`),
			dataIndex: "jobpozType",
			width: 150
		},
		{
			title: t(`${en_vi}.definitionCN`),
			dataIndex: "definitionCn",
			width: 200
		},
		{
			title: t(`${en_vi}.definitionEN`),
			dataIndex: "definitionEn",
			width: 200
		},
		{
			title: t(`${en_vi}.definitionVI`),
			dataIndex: "definitionVi",
			width: 200
		},
		{
			title: t(`${en_vi}.supplementaryExplanation`),
			dataIndex: "definitionExp",
			width: 250
		},
		{
			title: t("felix_ui.action"),
			key: "actions",
			fixed: "right",
			width: 220,
			render: (_, record) => (
				<TableAction
					actions={[
						{
							icon: IconEnum.EDIT,
							label: t("felix_ui.edit"),
							onClick: handleEdit.bind(record)
						},
						{
							icon: IconEnum.DELETE,
							label: t("felix_ui.delete"),
							popConfirm: {
								title: t("common.deleteMessage"),
								placement: "left",
								confirm: handleDelete.bind(null, record)
							}
						}
					]}
				></TableAction>
			)
		}
	];

	const [postTable, { reload }] = useTable({
		api: getPost,
		columns,
		showTableSetting: false,
		showIndexColumn: false
	});

	// Edit
	const handleEdit = (record: Recordable) => {
		openDrawerAddUpdate(true, { record, action: "edit" });
	};

	// Add
	const handleAdd = () => {
		openDrawerAddUpdate(true, { action: "add" });
	};

	// Delete
	const handleDelete = async ({ jobpozId }: any) => {
		try {
			await delPost(jobpozId);
			message.success(t("viewComponents.patientInformation.deleteSuccessfully"));
			reload();
		} catch (error) {
			t("viewComponents.patientInformation.deleteFailed");
		}
	};

	return (
		<div className="pagePosts">
			<div>
				<div className="box1">
					<h1 className="title">{t(`${en_vi}.postManagement`)}</h1>
					<Button type="primary" onClick={handleAdd}>
						+ Add Post
					</Button>
				</div>
				<BasicTable register={postTable}></BasicTable>
			</div>
			<DetailDrawer_AddUpdate reload={reload} register={drawer_add_update}></DetailDrawer_AddUpdate>
		</div>
	);
}
